<template>
  <el-card shadow="never" class="mb10">
    <el-row>
      <el-form ref="formQueryRef" :inline="true" :model="queryData">
        <el-form-item label="手机号码" prop="mobile">
          <el-input
            placeholder="请输入手机号码"
            v-model.trim="queryData.mobile"
            clearable
          />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select
            class="my-select"
            v-model.trim="queryData.status"
            placeholder="请选择状态"
            clearable
            @change="initData"
          >
            <el-option label="待审核" :value="3"> </el-option>
            <el-option label="审核通过" :value="4"> </el-option>
            <el-option label="审核不通过" :value="5"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="appTimes">
          <el-date-picker
            v-model="queryData.appTimes"
            type="datetimerange"
            clearable
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
      <div class="flex-right">
        <el-button type="primary" :icon="RefreshLeft" @click="resetForm">
          重置
        </el-button>
        <el-button
          type="primary"
          :icon="Search"
          class="ml20"
          @click="initData"
          v-enter="initData"
        >
          搜索
        </el-button>
      </div>
    </el-row>
  </el-card>
  <el-card shadow="never">
    <div class="mb10">
      <el-button type="primary" @click="onAudit(4)">+通过</el-button>
      <el-button type="danger" @click="onAudit(5)">驳回</el-button>
    </div>
    <el-table
      stripe
      border
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      key="id"
      @select="handleSelectionChange"
      @select-all="selectAll"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column
        v-for="item in options"
        :key="item.type"
        :prop="item.props"
        :type="item.type"
        :label="item.label"
        :width="item.width"
        :align="item.align"
        show-overflow-tooltip
        :fixed="item.fixed"
      >
        <template v-slot:default="{ row }" v-if="item.props === 'appTime'">
          {{ dayjs(row.appTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template v-slot:default="{ row }" v-if="item.props === 'status_desc'">
          <el-text :type="statusTypes[row.status]">
            {{ row.status_desc }}
          </el-text>
        </template>
        <template v-slot:default="{ row }" v-if="item.props === 'actions'">
          <el-button
            type="primary"
            size="small"
            text
            :disabled="row.status === 4"
            @click="onSingleAudit(row)"
          >
            通过
          </el-button>
          <el-button
            type="danger"
            size="small"
            text
            :disabled="row.status === 4"
            @click="onSingleRejected(row)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      class="mt-4"
      :total="total"
      :page-size="queryData.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </el-card>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { dayjs } from "element-plus";
import { Search, RefreshLeft } from "@element-plus/icons-vue";
import api from "@/api/auth.js";
import { options } from "./options.js";

const queryData = ref({
  pageNo: 1,
  pageSize: 10,
});
const statusTypes = { 4: "success", 5: "danger", 3: "primary" };
const formQueryRef = ref();
const loading = ref(false);
const total = ref(0);
const tableData = ref([]);
const auditList = ref([]);

const selectAll = (arr) => {
  // 是否全选
  if (arr.length !== 0) {
    // 全选
    arr.forEach((item) => {
      const bool = auditList.value.some((user) => user.id === item.id); // 存在返回true 否则返回false
      if (!bool) {
        // 不存在添加
        auditList.value.push(item);
      }
    });
  } else {
    // 取消全选
    tableData.value.forEach((item) => {
      auditList.value = auditList.value.filter((user) => user.id !== item.id);
    });
  }
};
const handleSelectionChange = (arr, row) => {
  // 选择
  const bool = auditList.value.some((user) => user.id === row.id); // 存在返回true 否则返回false
  if (bool) {
    // 存在删除
    auditList.value = auditList.value.filter((user) => user.id !== row.id);
  } else {
    // 添加
    auditList.value.push(row);
  }
};
const echoSelected = () => {
  // 回显选中
  setTimeout(() => {
    // 回显选中
    if (auditList.value.length > 0) {
      tableData.value.forEach((item) => {
        if (auditList.value.some((ele) => ele.id === item.id)) {
          tableRef.value.toggleRowSelection(item);
        }
      });
    }
  }, 500);
};

const initData = async () => {
  loading.value = true;
  try {
    const res = await api.authUserPage({
      ...queryData.value,
      appTimes: JSON.stringify(queryData.value.appTimes || []),
    });
    tableData.value = res.data.list;
    total.value = res.data.total;
    echoSelected();
  } finally {
    loading.value = false;
  }
};
const selectable = (row) => row.status === 3;

const handleCurrentChange = (val) => {
  queryData.value.pageNo = val;
  initData(queryData.value);
};
const handleSizeChange = (val) => {
  queryData.value.pageSize = val;
  initData(queryData.value);
};
const resetForm = () => {
  formQueryRef.value.resetFields();
};

const onAudit = (type) => {
  if (auditList.value.length) {
    ElMessageBox.confirm(
      `确认是否<span style='color:red;'>批量</span>审核<span style='color:red;'>${
        type === 4 ? "通过" : "不通过"
      }</span>`,
      "温馨提示",
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(async () => {
        const res = await api.authUserExamine({
          status: type,
          users: auditList.value,
        });
        if (res.data) {
          ElMessage.success(res.msg || `审核成功！`);
          handleCurrentChange(1);
        } else {
          ElMessage.error(res.msg || `审核失败！`);
        }
      })
      .catch(() => {});
  } else {
    ElMessage.error(`请先选择审核人员！`);
  }
};

const onSingleAudit = (row) => {
  ElMessageBox.prompt(
    `确认用户<span style='color:red;'>${
      row.nickname || ""
    }</span>是否审核<span style='color:red;'>通过？</span>`,
    "温馨提示",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      inputPattern: /^.+$/,
      inputValue: row.nickname,
      inputErrorMessage: "请输入用户名称",
      inputPlaceholder: "请输入用户名称",
    }
  )
    .then(async ({ value }) => {
      const res = await api.authUserExamine({
        status: 4,
        users: [{ nickname: value || row.nickname, id: row.id }],
      });
      if (res.data) {
        ElMessage.success(res.msg || `审核成功！`);
        handleCurrentChange(1);
      } else {
        ElMessage.error(res.msg || `审核失败！`);
      }
    })
    .catch(() => {});
};

const onSingleRejected = (row) => {
  ElMessageBox.confirm(
    `确认用户<span style='color:red;'>${row.nickname}</span>是否审核<span style='color:red;'>不通过？</span>`,
    "温馨提示",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      const res = await api.authUserExamine({
        status: 5,
        users: [{ nickname: row.nickname, id: row.id }],
      });
      if (res.data) {
        ElMessage.success(res.msg || `审核成功！`);
        handleCurrentChange(1);
      } else {
        ElMessage.error(res.msg || `审核失败！`);
      }
    })
    .catch(() => {});
};

onMounted(() => {
  initData();
});
</script>
